package com.wenhuang.chatgptopen.controller;

import com.wenhuang.chatgptopen.pojo.User;
import com.wenhuang.chatgptopen.retu.LoginReturn;
import com.wenhuang.chatgptopen.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/*
 *@Time：2023/5/20
 *@Author：Jelly
 */
@Controller
public class LoginController {

    //登录界面的业务
    @Autowired
    private UserService userService;
    private LoginReturn loginReturn;//返回给前端的对象
    private User userTemp;//查询后所得到的对象

    //登录验证

    @PostMapping("/login")
    @ResponseBody
    public LoginReturn login(User user, HttpServletResponse response) {

        //初始化loginReturn
        loginReturn = new LoginReturn();
        String message = "";
        boolean login = false;
        try {
            if ("".equals(user.getEmail())) {
                message = "请输入邮箱";
            } else if ("".equals(user.getPassword())) {
                message = "请输入密码";
            } else {
                //判断邮箱是否为kong
                if ((userService.verifyEmail(user)) != null) {//说明邮箱不为空
                    //检验密码是否正确
                    userTemp = userService.getUserByEmailAndPwd(user);
                    if ((userTemp) != null) {
                        //密码正确
                        message = "success";
                        loginReturn.autoInit(userTemp);
                        login = true;
                    } else {
                        //密码错误
                        message = "用户名或密码错误，请重新输入";
                    }
                } else {//说明邮箱为空
                    message = "该邮箱还未注册呢，请先注册";
                }
            }
            loginReturn.setLogin(login);
            loginReturn.setMessage(message);
            return loginReturn;
        }catch (Exception e) {
            response.setStatus(401);
            return null;
        }
    }
}